﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Roles = Medianamik.Core.Security.Roles;
using Medianamik.Globalization;

namespace Medianamik.UI.Controls 
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:RoleCheckBoxList runat=server></{0}:RoleCheckBoxList>")]
    public class RoleCheckBoxList : System.Web.UI.WebControls.CheckBoxList
    {
        [Bindable(true)]
        public IEnumerable<string> SelectedRoles
        {
            get
            {
                return ViewState["Selectedroles"] as IEnumerable<string> 
                    ?? new string[]{};
            }
            set
            {
                ViewState["Selectedroles"] = value;
                Select();
            }
        }

        public override string DataTextField
        {
            get
            {
                return "Text";
            }
            set
            {
                ;
            }
        }

        public override string DataValueField
        {
            get
            {
                return "Value";
            }
            set
            {
                ;
            }
        }

        public override object DataSource
        {
            get
            {
                return Roles.GetAllRoles()
                    .Select(g => new
                    {
                        Value = g,
                        Text = Translator.Translate("Medianamik_SecurityManagement", "Role_" + g) + " (" + g + ")"
                    }).OrderBy(g=>g.Text);
            }
            set
            {
                throw new Exception("Cannot set DataSource of this control");
            }
        }

        public override void DataBind()
        {
            base.DataBind();

            Select();

        }

        private void Select()
        {
            foreach (ListItem item in Items)
            {
                item.Selected = SelectedRoles.Any(r => r.Equals(item.Value, StringComparison.OrdinalIgnoreCase));
            }
        }
    }
}
